<template>
  <div class="flexContent">
    <div class="searchBox">
      <el-form ref="formRef" @submit.native.prevent :model="sForm" class="demo-form-inline" label-position="left"
        label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="账号">
                  <el-input v-clearEmoji v-model.trim="sForm.userName" clearable style="width: 95%" placeholder="请输入..."
                    @keyup.enter.native="searchFn" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" @click="addFn">新增</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="98%"
          size="medium" align="center">
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column field="userName" title="登录账号" min-width="150" />
          <vxe-column field="employeeName" title="姓名" min-width="150" />
          <vxe-column field="phone" title="手机号码" min-width="140" />
          <vxe-column field="higherName" title="负责人" width="120">
            <template v-slot="{ row }">
              <span v-if="row.higherName">{{ row.higherName }}</span>
              <span v-else>-</span>
            </template>
          </vxe-column>
          <vxe-column field="higherPhone" title="负责人电话" width="120">
            <template v-slot="{ row }">
              <span v-if="row.higherPhone">{{ row.higherPhone }}</span>
              <span v-else>-</span>
            </template>
          </vxe-column>
          <vxe-column field="roleNames" title="角色" width="120" />
          <vxe-column field="status" title="状态" width="120">
            <template v-slot="{ row }">
              <el-tag v-if="row.status == 0" type="success">在职</el-tag>
              <el-tag v-if="row.status == 1" type="info">离职</el-tag>
            </template>
          </vxe-column>
          <vxe-column fixed="right" min-width="200" title="操作">
            <template v-slot="{ row }">
              <el-button type="text" style="margin-right: 10px; color: rgb(0, 132, 255)"
                @click="editFn(row)">编辑</el-button>
              <el-button type="text" style="margin-right: 10px; color: rgb(0, 132, 255)"
                @click="resetPassword(row)">重置密码</el-button>
              <el-button type="text" style="color: red" v-if="row.status == '1'"
                @click="$delFn('商品', del, row)">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div>
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,->, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <AddDialog :close-on-click-modal="false" :show-dialog.sync="dialogTableVisible" width="50%" :title="title"
      @btnOk="btnOk" @close="close">
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
        <el-form-item label="姓名" style="width: 100%" prop="employeeName">
          <el-input v-model="addForm.employeeName" />
        </el-form-item>
        <el-form-item label="手机号码" style="width: 100%" prop="phone">
          <el-input v-model="addForm.phone" />
        </el-form-item>
        <el-form-item label="登录账号" style="width: 100%" prop="userName">
          <el-input v-model="addForm.userName" />
        </el-form-item>
        <el-form-item label="登录密码" v-if="title == '新增用户'" style="width: 100%" prop="password2">
          <el-input v-model="addForm.password2" type="password" show-password />
        </el-form-item>
        <el-form-item label="上级负责人" v-if="title == '编辑用户' && selected.roleCodes == 'ordinary'" style="width: 100%"
          prop="higherId">
          <el-select v-model="addForm.higherId" @click.native="getPrincipalList" popper-class="eloption" clearable
            filterable placeholder="请选择负责人">
            <el-option v-for="item in leaderList" :key="item.id" :value="item.id" :label="item.employeeName" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" style="width: 90%" prop="status">
          <el-radio-group v-model="addForm.status" size="small">
            <el-radio label="0">在职</el-radio>
            <el-radio label="1">离职</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </AddDialog>
  </div>
</template>

<script>
import md5 from "md5";
import { createUserInfo, queryUserInfo, getPrincipalList, editUserInfo, deleteUserInfo, resetPassword } from "@/api/userInfo";
import AddDialog from '@/components/Goods/AddDialog';
export default {
  name: "IndependentAccount",
  components: {
    AddDialog
  },
  data() {
    return {
      dialogTableVisible: false,
      title: '新增用户',
      sForm: {
        userName: "",
      },
      brandList: [],
      accountList: [],
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      selected: {},
      date: [],
      dialogArr: [],
      isSearch: false,
      allDataArr: [],
      addForm: {
        employeeName: '',
        phone: '',
        userName: '',
        password2: '',
        status: '0',
        higherId: ''
      },
      addRules: {
        employeeName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]+$/, message: '请输入中文', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/, message: '登录账号为手机号格式', trigger: 'blur' }
        ],
        password2: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: "长度在6到16个字符",
            trigger: "blur",
          },
          {
            pattern: /^[A-Za-z0-9]+$/,
            message: "请输入数字或字母",
            trigger: "blur",
          },
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' },
        ],
        higherId: [
          { required: true, message: '请选择上级联系人', trigger: 'change' }
        ]
      },
      leaderList: []
    };
  },
  created() {
    // this.getShopEasy();
    // this.getAllCount();
  },
  mounted() {
    this.queryUserInfo();
  },
  methods: {
    // 查找列表数据
    async queryUserInfo() {
      if (!this.isSearch) {
        this.sForm.userName = "";
      }
      const res = await queryUserInfo({
        ...this.page,
        ...this.sForm,
      });
      if (res.code === 200) {
        console.log(res.data, "data");
        this.accountList = res.data.list;
        this.page.total = res.data.total;
        // this.accountList = 
        const $table = this.$refs.xTable
        // console.log('$table', this.$refs.xTable);
        $table.loadData(this.accountList);
      }
    },
    // 搜索方法
    async searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = true;
      this.queryUserInfo();
    },
    async getPrincipalList() {
      const res = await getPrincipalList();
      if (res.code === 200) {
        this.leaderList = res.data
      }
    },
    // 重置
    resetFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = false;
      this.sForm.userName = "";
      this.queryUserInfo();
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;

      this.queryUserInfo();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.queryUserInfo();
    },
    close() {
      this.dialogTableVisible = false;
    },
    editFn(row) {
      this.getPrincipalList();
      this.title = '编辑用户'
      this.selected = row
      this.addForm.employeeName = row.employeeName
      this.addForm.phone = row.phone
      this.addForm.userName = row.userName
      this.addForm.status = row.status
      this.addForm.higherId = row.higherId
      console.log('this.selected', this.selected);
      this.dialogTableVisible = true
    },
    addFn() {
      this.title = '新增用户'
      this.dialogTableVisible = true
    },
    btnOk() {
      if (this.title == '编辑用户') {
        this.editUserInfo()
      } else {
        this.addUserInfo()
      }
    },
    addUserInfo() {
      this.$refs.addFormRef.validate(async (isOk) => {
        if (isOk) {
          console.log('11111', this.addForm);
          const password = md5(this.addForm.password2);
          const res = await createUserInfo({
            ...this.addForm,
            password: password,
          });
          if (res.code === 200) {
            this.$message.success("新增成功");
            this.close()
            this.queryUserInfo();
          } else {
            // this.$message.error(res.message);
          }
        } else {
          this.$message.warning("请检查输入信息");
        }
      });
    },
    async editUserInfo() {
      this.$refs.addFormRef.validate(async (isOk) => {
        if (isOk) {
          console.log('11111', this.addForm, this.selected.id);
          const res = await editUserInfo({
            ...this.addForm,
            id: this.selected.id
          });
          if (res.code === 200) {
            this.$message.success("修改成功");
            this.close()
            this.queryUserInfo();
          } else {
            // this.$message.error(res.message);
          }
        } else {
          this.$message.warning("请检查输入信息");
        }
      });
    },
    close() {
      this.addForm = {
        employeeName: '',
        phone: '',
        userName: '',
        password2: '',
        status: '0',
        higherId: ''
      }
      this.dialogTableVisible = false
      this.$refs.addFormRef.resetFields()
    },
    async del(row) {
      // console.log(row)
      const res = await deleteUserInfo({ id: row.id });
      if (res.code === 200) {
        this.$message.success(res.message);
        this.queryUserInfo();
      } else {
      }
    },
    resetPassword(row) {
      this.$confirm(`确认重置该用户密码吗, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          console.log('11111');
          const res = await resetPassword({ id: row.id });
          if (res.code === 200) {
            this.$message.success(res.message);
            this.queryUserInfo();
          }
        })
        .catch(() => { });
    }
  },
};
</script>

<style scoped lang="scss">
.inner {
  .item {
    p {
      display: flex;

      &:nth-child(1) {
        justify-content: space-between;
      }
    }
  }
}
</style>
